package br.com.pentagrama.service.impl;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class UploadThread extends Thread {

	private int BUFFER_SIZE = 128;
	
	private OutputStream bos = null;
	
	private Socket s;
	
	private long tamanho = 0;
	
	private String ipPorta;
	
	/**
	 * Método "get" para o atributo tamanho.
	 *
	 * @return Atributo tamanho
	 */
	public long getTamanho() {
		return tamanho;
	}

	public UploadThread(Socket socket, String ipPorta) {
		this.s = socket;
		this.ipPorta = ipPorta;
	}
	
	public UploadThread(Socket socket, OutputStream bos) {
		this.bos = bos;
		this.s = socket;
	}
	
	public void envioTCP(String ipPorta) {
		byte[] data1 = getData();
		DataOutputStream dos = null;
		try {
			OutputStream out = s.getOutputStream(); 
		    dos = new DataOutputStream(out);

		    while(true) {
		    	dos.write(data1);
				tamanho += data1.length;
		    }
		    
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				dos.flush();
				s.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void run() {

		try {
			envioTCP(ipPorta);
		} catch (Exception e) {
			//faz nada, upload terminado
		}
		
//		try {
//			byte[] data1 = getData();
//			String conteudo = getConteudo();
//			int i = 0;
//				
//			while(true) {
//				DataOutputStream data = new DataOutputStream(bos);
//				i++;
//				data.write(data1);
//				bos.flush();
//				data.close();
//				tamanho++;
//				data = null;
//			}
//			
//		} catch (IOException e) {
//			e.printStackTrace();
//		} finally {
//			if (bos != null) {
//				try {
//					bos.close();
//				} catch (IOException e) {
//				}
//			}
//		}
	}

	public String getConteudo() {
		StringBuilder texto = new StringBuilder();
		for (int i = 0; i < BUFFER_SIZE; i++) {
			texto.append("a");
		}
		return texto.toString();
	}
	public byte[] getData() {
		byte data[] = new byte[BUFFER_SIZE];
		for (int i = 0; i < data.length; i++) {
			data[i] = 'a'; 
		}
		return data;
	}
}
